// D66
<template>
  <div>
    <van-form class="d66">
      <van-field
        v-model="ruleForm.loginName"
        type="tel"
        maxlength="11"
        label="账号"
        placeholder="请填写账号"
        clearable
      />
      <van-field
        v-model="ruleForm.passWord"
        type="password"
        label="密码"
        placeholder="请填写密码"
        clearable
      />
      <van-field v-model="IntervalTime" type="tel" label="抢单间隔(s)" placeholder="请填写抢单间隔" clearable />
      <van-cell-group>
        <van-cell
          class="van-cell__tip"
          v-for="(content, index) in returnContent"
          :key="index"
          :title="content"
        />
      </van-cell-group>
    </van-form>
    <div class="popup-open__btn">
      <van-button type="warning">做单</van-button>
      <van-button type="danger" @click="onStart">{{ startFlag ? '停止接单' : '开始接单' }}</van-button>
    </div>
  </div>
</template>

<script>
import dayjs from "dayjs";
import { alertMsg, saveInfo, audio } from "@/utils/index";
import Fingerprint2 from "fingerprintjs2";
export default {
  name: "D66",
  props: {
    index: {
      type: String,
      default: ""
    },
    item: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      ruleForm: {
        loginName: "18857322772",
        logintoken: "",
        passWord: "a123456",
        uatoken: ""
      },
      IntervalTime: 10,
      startFlag: false,
      returnContent: [],
      isAcceptSuc: false,
      timer: null,
      activeIndex: ""
    };
  },
  watch: {
    // 监听接单状态
    startFlag() {
      if (this.item.index === 28 && this.index !== "") {
        this.$emit("changeOpened", {
          index: this.index,
          status: this.isAcceptSuc
            ? "已接单"
            : this.startFlag
            ? "已启动"
            : "待启动",
          startFlag: this.startFlag,
          content: this.returnContent
        });
      }
    },
    // 监听当前索引
    index() {
      if (this.item.index === 28 && this.index !== "") {
        this.activeIndex = this.index;
        // 获取保存账号信息
        this.ruleForm.loginName = this.item.user;
        this.ruleForm.passWord = this.item.pass;
        this.type = this.item.type || "0";

        // 如为 已接单 => 改变状态
        if (this.item.opened === "已接单") {
          this.$emit("changeOpened", {
            index: this.index,
            status: "待启动",
            startFlag: this.startFlag,
            content: this.returnContent
          });
        }
      }
    },
    returnContent() {
      if (this.returnContent.length >= 10) {
        this.returnContent = this.returnContent.filter((item, i) => i < 5);
      }
    }
  },
  created() {
    if (this.item.index === 28 && this.index !== "") {
      this.activeIndex = this.index;
      // 获取保存账号信息
      this.ruleForm.loginName = this.item.user;
      this.ruleForm.passWord = this.item.pass;
      this.type = this.item.type || "0";
    }
  },
  methods: {
    // 开始接单
    onStart() {
      const _this = this;
      if (!_this.startFlag) {
        _this.returnContent = [];
        _this.startFlag = true;
        _this.returnContent.unshift(alertMsg("正在登录"));
        // 获取logintoken
        this.$ajax({
          url:
            "https://d66td.com/king/get_login_token?_t=" +
            dayjs().millisecond() +
            "&_m=" +
            Math.random(),
          type: "post",
          ajaxData: {
            values: ""
          },
          dataType: "text",
          method: function(res) {
            _this.ruleForm.logintoken = res;
            let values = "";
            let excludes = {};
            excludes.userAgent = true;
            excludes.audio = true;
            excludes.fonts = true;
            excludes.canvas = true;
            let options = { excludes: excludes };
            Fingerprint2.get(options, function(components) {
              values = components.map(function(component) {
                return component.value;
              });
              _this.ruleForm.uatoken = Fingerprint2.x64hash128(
                values.join(""),
                31
              );
              // 登录
              _this.onLogin(_this);
            });
          }
        });
      } else {
        _this.onCancelQueue(_this);
      }
    },
    // 登录
    onLogin(_this) {
      clearInterval(_this.timer);
      window.api.ajax(
        {
          url:
            "https://d66td.com/king/login?_t=" +
            dayjs().millisecond() +
            "&_m=" +
            Math.random(),
          method: "post",
          headers: {
            "X-Requested-With": "XMLHttpRequest"
          },
          dataType: "json",
          returnAll: false,
          data: {
            values: _this.ruleForm
          }
        },
        res => {
          _this.returnContent.unshift(
            alertMsg(res.msg || "登录异常，正在重新登录")
          );
          if (res) {
            if (res.status) {
              // 登录成功  => 保存账号信息
              saveInfo({
                user: _this.ruleForm.loginName,
                pass: _this.ruleForm.passWord,
                type: _this.type,
                index: _this.index
              });
              // 登录成功
              _this.returnContent.unshift(alertMsg("正在努力为您接单..."));
              _this.onJoinQueue(_this);
            } else {
              _this.startFlag = false;
            }
          } else {
            _this.startFlag = false;
            _this.timer = setInterval(() => {
              _this.onLogin(_this);
            }, 2000);
          }
        }
      );
    },
    // 加入排队
    onJoinQueue(_this) {
      clearInterval(_this.timer);
      window.api.ajax(
        {
          url:
            "https://d66td.com/king/receive_task?y=0&msg=0&_t=" +
            dayjs().millisecond() +
            "&_m=" +
            Math.random(),
          method: "get",
          headers: {
            "X-Requested-With": "XMLHttpRequest"
          },
          dataType: "json",
          returnAll: false,
          data: {
            values: {}
          }
        },
        res => {
          if (res) {
            if (res.status) {
              _this.returnContent.unshift(alertMsg(res.Msg));
              _this.timer = setInterval(() => {
                _this.onJoinQueue(_this);
              }, _this.IntervalTime * 1000);
            } else {
              if (res.msg == "今日放弃任务次数过多明日再来把！") {
                _this.returnContent.unshift(alertMsg(res.msg));
                _this.startFlag = false;
              } else {
                _this.returnContent.unshift(alertMsg("接单成功"));
                _this.returnContent.unshift(
                  alertMsg("做完任务后请手动点击开始接单")
                );
                audio();
                _this.isAcceptSuc = true;
                _this.startFlag = false;
                _this.$emit("changeOpened", {
                  index: _this.activeIndex,
                  status: "已接单",
                  startFlag: false,
                  content: ["接单成功，请前往做单..."]
                });
              }
            }
          } else {
            _this.returnContent.unshift(alertMsg("正在排队中"));
            _this.timer = setInterval(() => {
              _this.onJoinQueue(_this);
            }, _this.IntervalTime * 1000);
          }
        }
      );
    },
    // 查询状态
    // onQueryReceiveTask(_this) {
    //   clearInterval(_this.timer);
    //   window.api.ajax(
    //     {
    //       url:
    //         "https://d66td.com/king/task/query_receive_task?reqid=" +
    //         _this.reqid +
    //         "&_t=" +
    //         dayjs().millisecond() +
    //         "&_m=" +
    //         Math.random(),
    //       method: "get",
    //       headers: {
    //         "X-Requested-With": "XMLHttpRequest"
    //       },
    //       dataType: "json",
    //       returnAll: false,
    //       data: {
    //         values: {}
    //       }
    //     },
    //     res => {
    //       _this.returnContent.unshift(alertMsg("暂无合适任务，继续接单..."));
    //       if (res) {
    //         if (res.Status) {
    //           // 查询接单状态
    //           _this.timer = setInterval(() => {
    //             _this.onQueryReceiveTask(_this);
    //           }, _this.IntervalTime * 1000);
    //         } else {
    //           alert(JSON.stringify(res));
    //         }
    //       } else {
    //         // 查询接单状态
    //         _this.timer = setInterval(() => {
    //           _this.onQueryReceiveTask(_this);
    //         }, _this.IntervalTime * 1000);
    //       }
    //     }
    //   );
    // },
    // 取消排队
    onCancelQueue(_this) {
      clearInterval(_this.timer);
      window.api.ajax(
        {
          url:
            "https://d66td.com/king/task/no_receive_task?&_t=" +
            dayjs().millisecond() +
            "&_m=" +
            Math.random(),
          method: "get",
          headers: {
            "X-Requested-With": "XMLHttpRequest"
          },
          dataType: "json",
          returnAll: false,
          data: {
            values: {}
          }
        },
        () => {
          _this.returnContent.unshift(alertMsg("接单取消"));
          _this.startFlag = false;
          _this.isAcceptSuc = false;
          _this.$toast({ message: "已停止接单" });
        }
      );
    }
  }
};
</script>
